<template>
  <div class="upload">
    <div class="upload-list">
      <div class="img-view"
           v-for="(item,index) in innerValue"
           :key="index"
           :style="{width: width+'px', height: height+'px'}">
        <el-image ref="preview"
                  :style="{width: width+'px', height: height+'px'}"
                  :src="item.url"></el-image>
        <div class="view"
             :style="{width: width+'px', height: height+'px'}">
          <i class="el-icon-view"
             style="color:#fff"
             :style="{fontSize:fontSize+'px'}"
             @click.stop="openViewer(index)"></i>
          <i class="el-icon-delete"
             style="color:#fff"
             v-if="!readonly"
             :style="{fontSize:fontSize+'px'}"
             @click.stop="handleRemove(index)"></i>
        </div>
      </div>
      <el-image v-if="readonly && !innerValue.length"
                :style="{width: width+'px', height: height+'px'}">
        <div slot="error"
             class="image-slot"
             :style="{width: width+'px', height: height+'px'}">
          <i class="el-icon-picture-outline"></i>

        </div>
      </el-image>
      <el-upload :action="api"
                 :show-file-list="false"
                 :file-list="innerValue"
                 :on-success="handleSuccess"
                 :before-upload="handleBeforeUpload"
                 accept="png,jpg,jpeg,gif,png"
                 :limit="maxLength"
                 :data="{'conentname':conentname,'seqnumber':seqnumber,'modelBusiName':modelBusiName}"
                 :headers="{Authorization}"
                 :multiple="maxLength-innerValue.length>1?true:false"
                 v-if="showUpload && !readonly"
                 :http-request="handleUpload">
        <div class="el-upload"
             :style="{width:width+'px',height:height+'px'}">
          <i class="el-icon-plus"></i>
        </div>
      </el-upload>
    </div>
    <p class="text"
       v-if="text">{{text}}</p>
    <!-- <el-image :style="{width: width+'px', height: height+'px'}">
      <div slot="error"
           class="image-slot"
           :style="{width: width+'px', height: height+'px',lineHeight: height+'px'}">
        <i class="el-icon-picture-outline"></i>
      </div>
    </el-image> -->
    <el-image-viewer v-if="showViewer"
                     :on-close="closeView"
                     :initialIndex="initialIndex"
                     :url-list="imgUrls"
                     z-index='9999' />

  </div>
</template>
<script>
import { cloneDeep } from 'lodash'
import lrz from "lrz";
export default {
  name: 'ym-upload-image',
  components: {
    ElImageViewer: () => import('element-ui/packages/image/src/image-viewer')
  },
  data () {
    return {
      imgUrls: [],
      showUpload: true,
      innerValue: [],
      imgList: [],
      showViewer: false,
      initialIndex: 0,
      Authorization: `Bearer ${localStorage.getItem('store/Authorization')}`
    }
  },
  props: {
    value: {},
    api: {
      type: String,
      default: '/file/uploadImage'
    },
    width: {
      type: [String, Number],
      default: 80
    },
    height: {
      type: [String, Number],
      default: 80
    },
    readonly: {
      type: Boolean,
      default: false
    },
    maxLength: {
      type: Number,
      default: 8
    },
    modelBusiName: {
      type: String,
      default: 'core'
    },
    conentname: {
      type: String,
      default: 'detail'
    },
    text: {
      type: String,
      default: ''
    },
    seqnumber: {
      default: new Date().getTime() % 10 + 1
    }
  },
  computed: {
    fontSize () {
      let val = 16;
      if (this.width > 80) {
        val = this.width / 80 * 16
      }
      return val
    }
  },
  watch: {
    value (curVal, oldVal) {
      this.init(curVal)
    }
  },
  created () {
    this.init(this.value)
  },
  methods: {
    init (curVal) {
      if (!curVal) {
        this.imgList = [];
        this.innerValue = [];
      } else {
        this.imgList = curVal.map(e => { return { url: e } })
        this.innerValue = curVal.map(e => { return { url: e } })
      }
      if (curVal.length >= this.maxLength) {
        this.showUpload = false
      } else {
        this.showUpload = true
      }
      if (curVal.length == 0) return
      this.imgUrls = curVal.map(e => { return e.url || e })
    },
    handleBeforeUpload (file) {
      const check = this.innerValue.length < this.maxLength;
      if (!check) {
        this.$notify({
          title: "最多上传" + this.maxLength + "张图",
          type: 'warning'
        });
        return check;
      }
      return new Promise((resolve, reject) => {
        lrz(file, { quality: 0.5, fieldName: file.name.slice(0, file.name.indexOf('.')) }).then(res => {
          resolve(res.file)
        }).catch((err) => {
          reject(err)
        })
      })
    },
    handleRemove (index) {
      this.innerValue.splice(index, 1)
      this.$emit("input", this.innerValue.map(v => { return v.url }));
    },
    handleSuccess (res, file) {
      let obj = res.data
      this.imgList.push({ url: obj });
      this.imgUrls.push({ url: obj })
      this.$emit("input", this.imgList.map(v => { return v.url }));
    },
    openViewer (index) {
      this.initialIndex = index;
      this.showViewer = true
    },
    closeView () {
      this.showViewer = false
    },
    handleUpload (e) {
      console.log(e)
      let form = new FormData()
      form.append('file', e.file)
      form.append('conentname', e.data.conentname)
      form.append('modelBusiName', e.data.modelBusiName)
      form.append('seqnumber', new Date().getTime())
      this.$command.execute({
        api: e.action,
        data: form
      }).then(res => {
        this.handleSuccess(res, e.file)
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.el-upload {
  border: 1px dashed #c0ccda;
  display: flex;
  align-items: center;
  border-radius: 4px;
  justify-content: center;
  background: #fbfdff;
}
.upload-list {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}
.img-view {
  position: relative;
  border-radius: 4px;
  overflow: hidden;
  margin-right: 10px;
  margin-bottom: 10px;
  border: 1px dashed #c0ccda;
  &:last-child {
    margin-right: 0px;
    margin-bottom: 0;
  }
  &:hover > .view {
    opacity: 1;
  }
}
.view {
  position: absolute;
  left: 0;
  top: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px dashed #c0ccda;
  i {
    margin: 0 5px;
    cursor: pointer;
  }
  opacity: 0;
  transition: all 0.2s;
}
/deep/.image-slot {
  background: #ddd;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 10px;
  i {
    font-size: 18px;
    display: block;
    color: #fff;
  }
}
.text {
  font-size: 12px;
  color: #999;
}
</style>
